<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/19
 * Time: 19:30
 */
namespace App\Services;

use App\Handlers\ApiResponse;
use App\Repositories\CardLogoRepository;
use App\Repositories\UserBankCardRepository;
use App\Repositories\UserRepository;

class BankCardService
{
    use ApiResponse;

    protected $userCreditCardRepository;
    protected $userBankCardRepository;
    protected $cardLogoRepository;

    public function __construct(UserRepository $userRepository, UserBankCardRepository $userBankCardRepository,
                                CardLogoRepository $cardLogoRepository)
    {
        $this->userRepository = $userRepository;
        $this->userBankCardRepository = $userBankCardRepository;
        $this->cardLogoRepository = $cardLogoRepository;
    }

    /**
     * 储蓄卡列表
     */
    public function bankCardList($userId)
    {
        $data = $this->userBankCardRepository->getBankCardList($userId);
        return $this->responseJson(0, $data);
    }

    /**
     * 解绑储蓄卡
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbindBankCard($id, $userId)
    {
        $bankIsExist = $this->userBankCardRepository->validateBankCardIsUser($id, $userId);
        if (empty($bankIsExist)) {
            return $this->responseJson(10307);//储蓄卡不存在
        } else {
            $userBankCardRepository = $this->userBankCardRepository->byId($id);
            $userBankCardRepository->update(['is_bind' => 0, 'update_time' => time()]);
            return $this->responseJson(0);
        }
    }

    /**
     * 解绑储蓄卡
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function defaultBankCard($id, $userId)
    {
        $bankIsExist = $this->userBankCardRepository->validateBankCardIsUser($id, $userId);
        if (empty($bankIsExist)) {
            return $this->responseJson(10307);//储蓄卡不存在
        } else {
            //找出已经设置为默认的卡
            $alreadyDefaultCard = $this->userBankCardRepository->findDefaultCardAll($userId);
            if (!empty($alreadyDefaultCard)) {
                foreach ($alreadyDefaultCard as $value) {
                    $modifyUndefaultCard = $this->userBankCardRepository->byId($value['id']);
                    $modifyUndefaultCard->update(['is_default' => 0, 'update_time' => time()]);
                }
            }
            $userBankCardRepository = $this->userBankCardRepository->byId($id);
            $userBankCardRepository->update(['is_default' => 1, 'update_time' => time()]);
            return $this->responseJson(0);
        }
    }


}
